package com.sky.interceptor;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.AccountNotFoundException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
//    String token;
    /*
    在业务处理器处理请求之前被调用。
    在请求contrller之前调用方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 ：获取请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截的url:{}",requestURI);
        //2 ：我们之拦截动态资源，不拦截静态资源
        //静态资源：HTML , CSS , IMAGE
        if (!(handler instanceof HandlerMethod)){
            return true;// 直接放行静态资源
        }

        // 3 ： 获取token 从请求头里面获取token

        String token = request.getHeader("token");
        log.info("token令牌:{}",token);
        // 说明用户没有登录
        if (null == token){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_LOGIN);
        }
        // 如果用户已经登录
        Claims claims = JwtUtil.parseJWT("sxx", token);
        // 获取用户id,一会在进行修改用户密码的时候可以使用
        Long empId = Long.valueOf(claims.get("empId").toString());
        log.info("当前已经登录用户id：{}",empId);
        //把当前登录用户的id存到上下文环境里面
        BaseContext.setCurrentId(empId);

        // 放行
        return true;
    }
    /*
    在请求contrller之后调用方法
     */
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
////        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//        System.out.println("postHandle");
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
////        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//        System.out.println("afterCompletion");
//    }
}
